package com.ym.pms.service.impl;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.codec.Base64;
import com.itextpdf.tool.xml.XMLWorkerFontProvider;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import com.ym.pms.dao.BunkMapper;
import com.ym.pms.dao.UserMapper;
import com.ym.pms.model.Bunk;
import com.ym.pms.model.Contract;
import com.ym.pms.model.SysUser;
import com.ym.pms.model.User;
import com.ym.pms.service.ContractServices;
import com.ym.pms.service.SysUserService;
import com.ym.pms.utils.JSONResult;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import sun.misc.BASE64Encoder;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: xybh
 * @Description:
 * @Date: Created in 21:21 2021/1/4
 * @Modified:
 */
@Service
public class PdfService {

    @Autowired
    private ContractServices contractService;
    @Resource
    private SysUserService sysUserService;
    @Autowired
    private BunkMapper bunkMapper;

    private static Configuration freemarkerCfg = null;

    @Value("${HTML}")
    private String html;
    @Value("${FONT}")
    private String font;

    public void createContract(Integer id) {
        //需要填充的数据
        Map<String, Object> data = new HashMap<>(16);
        Contract contract = contractService.queryOne(id);

        SysUser user = sysUserService.findUserByUserId(contract.getCoUid().longValue());

        Bunk bunk = bunkMapper.selectByPrimaryKey(contract.getCoBkCoding());
        data.put("username", contract.getCoPBName());
        data.put("userNo", user.getUIno());
        data.put("coDeposit", contract.getCoDeposit());
        data.put("coRent", contract.getCoRent());
        data.put("coRDtime", contract.getCoRDtime());
        data.put("coPCosts", contract.getCoPCosts());
        data.put("coBEtime", contract.getCoBETime());
        data.put("coMtime", contract.getCoMtime());
        data.put("coLD", contract.getCoLD());
        data.put("coGtime", contract.getCoGtime());
        data.put("bkPayArea", bunk.getBkPayarea());


        String dest = "/www/wwwroot/pms/contract/" + id + ".pdf";
        String content = freeMarkerRender(data, html);
        //创建pdf
        try {
            createPdf(content, dest);
        } catch (IOException | DocumentException e) {
            e.printStackTrace();
        }
    }

    public String getPdf(Integer id) {
        String dest = "/www/wwwroot/pms/contract/" + id + ".pdf";
        return Base64.encodeFromFile(dest);
    }

    /**
     * 读取本地pdf,这里设置的是预览
     */
    public void readPdf(HttpServletResponse response, String dest) {
        response.reset();
        response.setContentType("application/pdf");
        try {
            File file = new File(dest);
            FileInputStream fileInputStream = new FileInputStream(file);
            OutputStream outputStream = response.getOutputStream();
            IOUtils.write(IOUtils.toByteArray(fileInputStream), outputStream);
            response.setHeader("Content-Disposition",
                    "inline; filename= file");
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public void createPdf(String content, String dest) throws IOException, DocumentException {
        // step 1
        Document document = new Document();
        // step 2
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(dest));
        // step 3
        document.open();
        // step 4
        XMLWorkerFontProvider fontImp = new XMLWorkerFontProvider(XMLWorkerFontProvider.DONTLOOKFORFONTS);
        fontImp.register(font);
        XMLWorkerHelper.getInstance().parseXHtml(writer, document,
                new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8)), null, StandardCharsets.UTF_8, fontImp);
        // step 5
        document.close();

    }

    /**
     * freemarker渲染html
     */
    public String freeMarkerRender(Map<String, Object> data, String htmlTmp) {
        Writer out = new StringWriter();

        try {
            // 获取模板,并设置编码方式
            setFreemarkerCfg();
            Template template = freemarkerCfg.getTemplate(htmlTmp);
            template.setEncoding("UTF-8");
            //将合并后的数据和模板写入到流中，这里使用的字符流
            template.process(data, out);
            out.flush();
            return out.toString();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 设置freemarkerCfg
     */
    private void setFreemarkerCfg() {
        freemarkerCfg = new Configuration();
        //freemarker的模板目录
        try {
            freemarkerCfg.setDirectoryForTemplateLoading(new File("/www/wwwroot/pms"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
